package com.lo.common;

import com.lo.dao.UserMapper;
import com.lo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

@Component
public class RedisFollowHelper {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserMapper userMapper;

    //明星用户（FOLLOW_USERS） 的粉丝表
    private static final String MY_FANS = "USER_%s:myFans";
    //粉丝用户（FANS_USERS） 的关注表
    private static final String MY_FOLLOWS = "USER_%s:myFollows";

    //user去关注别人，判断是followId否已关注
    public boolean isFollowed(Long followId, Long userId){
        String fanUsersKey = String.format(MY_FOLLOWS,userId);
        Object value = redisUtil.score(fanUsersKey,String.valueOf(followId));
        return value!=null;
    }

    //关注方法
    public void follow(Long followId,Long userId){
        //根据Id获取要关注人的信息
//        List<User>users = userMapper.selectById(followId);
//        User followUser = users.get(0);
        //向被关注者的粉丝列表中添加user
        String followUsersKey = String.format(MY_FANS,followId);
        redisUtil.sZSet(followUsersKey,userId.toString(),System.currentTimeMillis());
        //向关注者的关注列表中添加followid
        String fanUsersKey = String.format(MY_FOLLOWS,userId);
        redisUtil.sZSet(fanUsersKey,followId.toString(),System.currentTimeMillis());
    }
    //取消关注方法
    public void unFollow(Long followId,Long userId){
        //移除粉丝表中的userid
        String followUsersKey = String.format(MY_FANS,followId);
        redisUtil.removeZSet(followUsersKey,userId.toString());
        //移除关注表中的followid
        String fansUserKey = String.format(MY_FOLLOWS,userId);
        redisUtil.removeZSet(fansUserKey,followId.toString());
    }
    //获取关注列表方法
    public Set<String> myFollows(Long userId){
        String fanUsersKey = String.format(MY_FOLLOWS,userId);
        Set<String> idSet = redisUtil.revRange(fanUsersKey,0,-1);
        return idSet;
    }
    //获取粉丝列表方法
    public Set<String> myFans(Long followId){
        String followUsersKey = String.format(MY_FANS,followId);
        Set<String> idSet = redisUtil.revRange(followUsersKey,0,-1);
        return idSet;
    }
    //获取我的关注数量
    public Long myFollowCount(Long userId){
        String fanUsersKey = String.format(MY_FOLLOWS,userId);
        Long followCount = redisUtil.sizeZSet(fanUsersKey);
        return followCount;
    }
    //获取我的粉丝数量
    public Long myFansCount(Long followId){
        String followUsersKey = String.format(MY_FANS,followId);
        Long fansCount = redisUtil.sizeZSet(followUsersKey);
        return fansCount;
    }




}
